<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace think\template\taglib\api;

use think\Db;
use app\home\logic\FieldLogic;

/**
 * 栏目基本信息
 */
class TagType extends Base
{
    public $fieldLogic;

    //初始化
    protected function _initialize()
    {
        parent::_initialize();
        $this->fieldLogic = new FieldLogic();
        if ($this->aid > 0) { // 应用于文档详情页
            $this->tid = Db::name('archives')->where('aid', $this->aid)->cache(true, EYOUCMS_CACHE_TIME, "archives")->getField('typeid');
        }
    }

    /**
     * 获取指定频道的的所有栏目列表
     */
    public function getAllType($param = [], $typeid = '', $channelid = 2)
    {
        //跟随后台分类设置   一级 = 1 二级 = 2 三级 = 3
        $type = getUsersConfigData('shop.shop_arctype_level');
        $type = empty($type) ? 1 : $type;
        $channelid = empty($channelid) ? 2 : $channelid;
        if (1 == $channelid) {
            $type = 2;
        }
        //一级
        $where['topid'] = 0;
        $where['grade'] = 0;
        $where['is_hidden'] = 0;
        $where['is_del'] = 0;
        $where['status'] = 1;
        $where['current_channel'] = $channelid;

        $list = Db::name('arctype')->where($where)->order('sort_order asc')->getAllWithIndex('id');
        $list = get_ad_link_url($list);
        foreach ($list as $k => $v) {
            if (!empty($v['ad_image'])) $list[$k]['ad_image'] = $this->get_default_pic($v['ad_image']);
            $list[$k]['litpic'] = $this->get_default_pic($v['litpic']);
            $list[$k]['child'] = [];
        }

        $type_ids = get_arr_column($list, 'id');
        //二级
        if (2 == $type) {
            unset($where['topid']);
            $where['grade'] = 1;
            $where['parent_id'] = ['in', $type_ids];
            $se_list = Db::name('arctype')->where($where)->order('sort_order asc')->select();
            if (!empty($se_list)) {
                $se_list = get_ad_link_url($se_list);
                foreach ($se_list as $k => $v) {
                    $v['is_on'] = 0;
                    $v['litpic'] = $this->get_default_pic($v['litpic']);
                    $list[$v['parent_id']]['child'][$v['id']] = $v;
                }
            }
        } else if (3 == $type) {
            //三级
            unset($where['topid']);
            $where['grade'] = ['in', [1, 2]];
            $where['parent_id|topid'] = ['in', $type_ids];
            $se_list = Db::name('arctype')->where($where)->order('grade asc,sort_order asc')->select();
            if (!empty($se_list)) {
                $se_list = get_ad_link_url($se_list);
                foreach ($se_list as $k => $v) {
                    $v['is_on'] = 0;
                    $v['litpic'] = $this->get_default_pic($v['litpic']);
                    if (1 == $v['grade']) {
                        $list[$v['parent_id']]['child'][$v['id']] = $v;
                    } else {
                        $list[$v['topid']]['child'][$v['parent_id']]['child'][] = $v;
                    }
                }
            }
        }
        $list = array_merge($list);
        foreach ($list as $k => $v) {
            if (!empty($v['child'])) {
                foreach ($v['child'] as $m => $n) {
                    if (!empty($n['child'])) {
                        $v['child'][$m]['child'] = array_merge($n['child']);
                    }
                }
                $list[$k]['child'] = array_merge($v['child']);
            }
        }

        //第一个typeid,几级分类取几级的
        $first_typeid = 0;
        $first_typename = '';
        if (1 == $type && !empty($list[0])) {
            $list[0]['is_on'] = 1;
            $first_typeid = !empty($list[0]['id']) ? $list[0]['id'] : 0;
            $first_typename = !empty($list[0]['typename']) ? $list[0]['typename'] : '';
        } elseif (2 == $type && !empty($list[0]['child'][0]['id'])) {
            $list[0]['child'][0]['is_on'] = 1;
            $first_typeid = !empty($list[0]['child'][0]['id']) ? $list[0]['child'][0]['id'] : 0;
            $first_typename = !empty($list[0]['child'][0]['typename']) ? $list[0]['child'][0]['id'] : '';
        } elseif (3 == $type && !empty($list[0]['child'][0]['child'][0])) {
            $list[0]['child'][0]['child'][0]['is_on'] = 1;
            $first_typeid = !empty($list[0]['child'][0]['child'][0]['id']) ? $list[0]['child'][0]['child'][0]['id'] : 0;
            $first_typename = !empty($list[0]['child'][0]['child'][0]['typename']) ? $list[0]['child'][0]['child'][0]['typename'] : '';
        }

        return ['list' => $list, 'first_typeid' => $first_typeid, 'first_typename' => $first_typename, 'type' => $type];
    }

    /**
     * 获取栏目基本信息
     * @author wengxianhu by 2018-4-20
     */
    public function getType($typeid = '', $type = 'self', $addfields = '', $infolen = '', $suffix = true)
    {
        $typeid = !empty($typeid) ? $typeid : $this->tid;
        if (empty($typeid)) {
            $redata = [
                'data' => false,
            ];
            return $redata;
        }

        $cacheKey = 'api-' . md5(__CLASS__ . __FUNCTION__ . json_encode(func_get_args()));
        $redata = cache($cacheKey);
        if (!empty($redata['data'])) { // 启用缓存
            return $redata;
        }

        switch ($type) {
            case 'top':
                $result = $this->getTop($typeid);
                break;

            default:
                $result = $this->getSelf($typeid, $addfields);
                break;
        }
        isset($result['litpic']) && $result['litpic'] = $this->get_default_pic($result['litpic']);
        isset($result['seo_title']) && $result['seo_title'] = $this->set_arcseotitle($result['typename'], $result['seo_title']);
        if (!empty($infolen) && !empty($result['seo_description'])) {
            $result['seo_description'] = text_msubstr($result['seo_description'], 0, $infolen, $suffix);
        }
        $result = $this->fieldLogic->getTableFieldList($result, config('global.arctype_channel_id'));
        /*当前单页栏目的内容信息*/
        $result['current_typeid'] = $typeid;
        if (!empty($addfields) && $result['current_channel'] == 6) {
            $addfields = str_replace('，', ',', $addfields); // 替换中文逗号
            $addfields_arr = explode(",", $addfields);
            if (in_array('content', $addfields_arr) && !in_array('content_ey_m', $addfields_arr)) {
                $addfields .= ",content_ey_m";
            }
            $addfields = trim($addfields, ',');
            $rowExt = Db::name('single_content')->field($addfields)->where('typeid', $result['id'])->find();
            $rowExt = $this->fieldLogic->getChannelFieldList($rowExt, $result['current_channel'], false, true);

            if (isset($rowExt['content']) && isset($rowExt['content_ey_m']) && empty($rowExt['content'])) {
                $rowExt['content'] = $rowExt['content_ey_m'];
            } else if (isset($rowExt['content']) && isset($rowExt['content_ey_m']) && empty($rowExt['content']) && empty($rowExt['content_ey_m'])) {   //当前栏目内容为空，从下级栏目读取
                $type_arr = Db::name("arctype")->where(['parent_id' => $result['typeid'], 'is_del' => 0])->getField('id', true);
                $rowNext = Db::name('single_content')->field('typeid,content,content_ey_m')->where(['typeid' => ['in', $type_arr], 'content|content_ey_m' => ['neq', '']])->find();
                if (!empty($rowNext)) {
                    $rowNext = $this->fieldLogic->getChannelFieldList($rowNext, $result['current_channel'], false, true);
                    if (!empty($rowNext['content_ey_m'])) {
                        $rowExt['content'] = $rowNext['content_ey_m'];
                    } else {
                        $rowExt['content'] = $rowNext['content'];
                    }
                    $rowExt['current_typeid'] = $rowNext['typeid'];
                }
            }
            //限制content的长度  html_msubstr
            if (!empty($rowExt['content']) && !empty($infolen)) {
                $rowExt['content'] = html_msubstr($rowExt['content'], 0, $infolen, $suffix);
            }
            is_array($rowExt) && $result = array_merge($result, $rowExt);
        }
        /*--end*/

        $redata = [
            'data' => !empty($result) ? $result : false,
        ];
        cache($cacheKey, $redata, null, 'arctype');

        return $redata;
    }

    /**
     * 获取当前栏目基本信息
     * @author wengxianhu by 2018-4-20
     */
    public function getSelf($typeid, $addfields = '')
    {
        $field = 'id,id as typeid,typename,current_channel,parent_id,topid,grade,litpic,seo_title,seo_keywords,seo_description';
        $result = Db::name('arctype')->field($field)
            ->where(['id' => $typeid])
            ->find();

        return $result;
    }

    /**
     * 获取当前栏目的第一级栏目基本信息
     * @author wengxianhu by 2018-4-20
     */
    public function getTop($typeid)
    {
        $parent_list = model('Arctype')->getAllPid($typeid); // 获取当前栏目的所有父级栏目
        $result = current($parent_list); // 第一级栏目

        return $result;
    }

    //获取帮助下的分类和文章
    public function getHelpTypeList($param = [], $typeid = '')
    {
        $field = 'id,typename,current_channel,parent_id,topid,grade,litpic,seo_title,seo_keywords,seo_description';
        $type_list = Db::name('arctype')->field($field)->where(['parent_id' => $typeid])->getAllWithIndex('id');
        $typeids = get_arr_column($type_list,'id');
        $where['typeid'] = ['in',$typeids];
        $where['arcrank'] = 0;
        $where['status'] = 1;
        $where['is_del'] = 0;
        $arc_data = Db::name('archives')->field('aid,title,litpic,typeid')
            ->where('typeid','in',$typeids)->order('sort_order asc,aid desc')->select();
        if (!empty($arc_data)){
            foreach ($arc_data as $k => $v){
                $v['litpic'] = $this->get_default_pic($v['litpic']);
                $type_list[$v['typeid']]['data'][] = $v;
            }
        }
        return $type_list;
    }
}